<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/7/20 22:15
 */

namespace module\chat\logic;

use module\chat\model\Message;
use module\chat\model\Unlimited;
use module\user\model\User;
use mof\annotation\Inject;
use mof\interface\UserInterface;
use mof\Logic;

class UnlimitedLogic extends Logic
{
    #[Inject(Unlimited::class)]
    protected $model;

    /**
     * @var User 当前对话用户
     */
    protected UserInterface $user;

    public function withUser(UserInterface $user): static
    {
        $this->user = $user;
        return $this;
    }

    /**
     * 获取会话列表
     * @return array
     */
    public function list(): array
    {
        return $this->model
            ->where('user_id', $this->user->id)
            ->order('id', 'desc')
            ->select()
            ->toArray();
    }

    public function create($name = '新的对话'): \mof\Model
    {
        return parent::save([
            'user_id' => $this->user->id,
            'name'    => $name
        ]);
    }

    public function rename($id, $name): \mof\Model
    {
        return parent::update($id, [
            'name' => $name
        ]);
    }

    public function delete($id): bool
    {
        if ($result = parent::delete($id)) {
            //删除对话记录
            Message::where([
                'user_id'     => $this->user->id,
                'object_type' => 'unlimited',
                'object_id'   => $id,
            ])->delete();
        }
        return $result;
    }
}